package com.bluesimon.wbf.view;

import com.alibaba.fastjson.JSON;
import com.bluesimon.wbf.Principle;
import com.bluesimon.wbf.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Django on 2017/7/16.
 */
public abstract class AbstractPageDataTunnel implements IPageDataTunnel {

    protected static HashMap<String, List<String>> moduleToApis = new HashMap<>();

    private static Log logger = LogFactory.getLog(AbstractPageDataTunnel.class);

    @Override
    public List<String> getApisByModule(String module) {
        return moduleToApis.get(module);
    }

    /**
     * 设置api上的参数
     *
     * @param m
     * @param api
     * @param principle
     * @return
     */
    protected String preDoGet(String m, String api, Principle principle) {
        Pattern p = Pattern.compile("\\w*\\{[\\w|=]*\\}\\w*");
        Matcher matcher = p.matcher(api);
        while (matcher.find()) {
            String match = matcher.group();
            //去头去尾,去掉外层{}
            String matchVal = match.substring(1, match.length() - 1);
            String key = matchVal;
            String def = "";
            int eq = matchVal.indexOf("=");
            if (eq > -1) {
                key = matchVal.substring(0, eq);
                def = matchVal.substring(eq + 1, matchVal.length());
            }
            String real = principle.get(key);
            if (StringUtils.isEmpty(real)) {
                real = def;
            }
            api = api.replace(match, real);
        }
        return api;
    }

    /**
     * 用户自定义解析api
     *
     * @param m
     * @param api
     * @param principle
     * @return
     */
    public abstract String proDoGet(String m, String api, Principle principle);

    /**
     * 组装模块的数据
     *
     * @param module
     * @param principle
     * @return
     */
    @Override
    public List<JSON> assemblePageData(String module, Principle principle) {
        List<JSON> resps = new ArrayList<>();
        List<String> apis = this.getApisByModule(module);
        if (apis != null && apis.size() > 0) {
            for (String api : apis) {
                String preUrl = preDoGet(module, api, principle);
                String url = proDoGet(module, preUrl, principle);
                String[] respx = from(url);
                JSON json = null;
                String code = respx[0];
                String message = respx[1];
                if (Integer.parseInt(code) == 200) {
                    try {
                        Object ojson = JSON.parse(respx[1]);
                        if (ojson instanceof JSON) {
                            json = (JSON) ojson;
                        }
                    } catch (Exception e) { //为非json字符
                        Response<String> exResp = new Response<String>();
                        exResp.setCode(code);
                        json = (JSON) JSON.toJSON(exResp);
                    }
                } else {
                    logger.error(code + "====" + message);
                    Response<String> exResp = new Response<String>();
                    exResp.setCode(code);
                    exResp.setMessage(message);
                }
                resps.add(json);
            }
        }
        return resps;
    }

    /**
     * 从接口获取数据
     *
     * @param api
     * @return
     */
    private String[] from(String api) {
        String[] resp = {"500", ""};
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(api);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                resp[0] = String.format("%d", response.getStatusLine().getStatusCode());
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    resp[1] = EntityUtils.toString(entity);
                }
            } catch (Exception ex) {
                resp[1] = ex.getMessage();
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resp;
    }

}
